package com.klxedu.ms.gateway.event;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.klxedu.ms.gateway.AuthServerConstants;

public abstract class Event {

	private String userID;
	private String loginID;
	private Date eventDate;
	private String ip;
	private String terminal;
	private String origin;
	private String subject;

	public Event(HttpServletRequest request, String origin, String subject) {
		this.userID = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_USERID);
		this.loginID = (String) request.getSession().getAttribute(AuthServerConstants.SESSION_KEY_LOGINID);
		this.ip = getIpAddr(request);
		this.terminal = request.getHeader("User-Agent");
		this.eventDate = new Date();
		this.origin = origin == null || "".equals(origin) ? "PC" : origin.toUpperCase();
		this.subject = subject;
	}

	public String getUserID() {
		return userID;
	}

	public void setUserID(String userID) {
		this.userID = userID;
	}

	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public Date getEventDate() {
		return eventDate;
	}

	public void setEventDate(Date eventDate) {
		this.eventDate = eventDate;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getTerminal() {
		return terminal;
	}

	public void setTerminal(String terminal) {
		this.terminal = terminal;
	}

	public String getOrigin() {
		return origin;
	}

	public void setOrigin(String origin) {
		this.origin = origin;
	}
	
	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	private String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip != null ? ip.split(",")[0] : ip;
	}

	@Override
	public String toString() {
		return "Event [userID=" + userID + ", loginID=" + loginID + ", eventDate=" + eventDate + ", ip=" + ip
				+ ", terminal=" + terminal + ", origin=" + origin + ", subject=" + subject + "]";
	}

	
}
